package com.example.ykbboom.testasynctask;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new TestAsyncTask().execute();
    }
    class TestAsyncTask extends AsyncTask<Void,Integer,Boolean>{
        /**
         * 组件初始化
         * */
        @Override
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setTitle("下载");
            progressDialog.setMessage("载入中...");
            progressDialog.setCancelable(false);
            progressDialog.show();
        }
        /**
         * 执行耗时任务，子线程
         * */
        @Override
        protected Boolean doInBackground(Void... params) {
            int number = 0;
            try {
                while (true){
                    publishProgress(number);//调用onProgressUpdate()
                    Thread.sleep(1000);
                    number = number + 10;
                    if (number>=100){
                        break;
                    }
                }
            } catch (Exception e) {
                return  false;
            }
            return true;
        }
        /**
         * 更新UI组件
         * */
        @Override
        protected void onProgressUpdate(Integer... values) {
            int a = values[0];
            Log.d("test",String.valueOf(a));
            progressDialog.setMessage("载入中..."+values[0]+"%");
        }
        /**
         * 收尾工作
         * */
        @Override
        protected void onPostExecute(Boolean aBoolean) {
            progressDialog.dismiss();
            if (aBoolean){
                Toast.makeText(MainActivity.this,"下载完成",Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(MainActivity.this,"下载失败",Toast.LENGTH_SHORT).show();
            }
        }




    }
}
